package crew.gwt.client.widgets.util;

import java.util.List;

import crew.gwt.client.domain.PersistableEntity;
import crew.gwt.client.services.util.ServerCall;
import crew.gwt.client.widgets.CrewListBox;

public abstract class EntityListBox<T extends PersistableEntity<T>> extends CrewListBox 
{
	private List<T> entities = null;
	private T entityToSelect = null;
	private ServerCall<List<T>> callToFillEntities = null; 
	
	public EntityListBox(boolean multi) {
		super(multi);
	}	

	public void loadEntities() {
		this.callToFillEntities.call();
	}

	protected void showList() {
		clear();
		for(T e : entities){
			addItem(e.getId().toString());
		}
		if(entityToSelect != null){
			setSelectedEntity(entityToSelect);
			entityToSelect = null;
		}
	}
	
	public T getSelectedEntity(){
		if(getSelectedIndex()!= -1){
			return entities.get(getSelectedIndex());
		}
		return null;
	}

	public void setSelectedEntity(T entityToSelect){
		if( entityToSelect != null && entities != null && entities.contains(entityToSelect) ){
			setSelectedIndex(entities.indexOf(entityToSelect));
		}
		else
			this.entityToSelect = entityToSelect;
	}
	
	public List<T> getEntities() {
		return entities;
	}

	public ServerCall<List<T>> getCallToFillEntities() {
		return callToFillEntities;
	}

	public void setEntities(List<T> entities) {
		this.entities = entities;
	}

	public void setCallToFillEntities(ServerCall<List<T>> callToFillEntities) {
		this.callToFillEntities = callToFillEntities;
	}

	public T getEntityToSelect() {
		return entityToSelect;
	}

	public void setEntityToSelect(T entityToSelect) {
		this.entityToSelect = entityToSelect;
	}
}
